<template>
  <el-dialog
    v-model="visible"
    :modal="false"
    :title="$t('product.uploadTips')"
    :close-on-click-modal="false"
    width="38%"
    custom-class="prod-upload-dialog"
  >
    <p>{{ $t('product.uploadProdTip') }}</p>
    <p>{{ $t('product.uploadProdTip2') }}</p>
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      :action="http.adornUrl('/prod/prod/exportExcel')"
      :headers="{ Authorization: cookie.get('bbcAuthorization_vs'),locale:lang }"
      :limit="1"
      name="excelFile"
      :on-preview="handlePreview"
      :on-error="uploadFalse"
      :on-progress="onProgress"
      :on-success="uploadSuccess"
      :file-list="files"
      :auto-upload="false"
      :before-upload="beforeAvatarUpload"
    >
      <template #tip>
        <div class="el-upload__tip" />
      </template>
      <template #trigger>
        <div class="default-btn primary-btn">
          {{ $t("product.selectFile") }}
        </div>
      </template>
      <div
        class="default-btn download-btn"
        @click="submitUpload"
      >
        {{ $t("product.import") }}
      </div>
      <div
        class="default-btn download-btn"
        @click="downloadModel"
      >
        {{ $t("product.downloadTemplate") }}
      </div>
    </el-upload>
  </el-dialog>
</template>
<script setup>
import cookie from 'vue-cookies'
import http from '@/utils/http.js'
import { ElMessage, ElLoading } from 'element-plus'
const emit = defineEmits(['refreshDataList'])
const props = defineProps({
  isLoad: {
    type: Boolean,
    default: false
  }
})

const lang = localStorage.getItem('bbcLang') || 'zh_CN'

let loading = null
const onProgress = () => {
  if (!loading && props.isLoad) {
    loading = ElLoading.service({
      lock: true,
      target: '.prod-upload-dialog',
      customClass: 'prod-upload-load'
    })
  }
}

const files = ref([])
const uploadSuccess = (response) => {
  if (loading && props.isLoad) {
    loading.close()
    loading = null
  }

  setTimeout(() => {
    alert(response.data)
  }, 10)
  files.value = []
  visible.value = false
  emit('refreshDataList')
}
const uploadFalse = (response) => {
  alert(response.data || $t('product.fileUploadFail'))
}

const visible = ref(false)
const init = () => {
  visible.value = true
}
// 上传前对文件的大小的判断
let upload = false
const beforeAvatarUpload = (file) => {
  upload = true
  const extension = file.name.split('.')[1] === 'xls'
  const extension2 = file.name.split('.')[1] === 'xlsx'
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!extension && !extension2) {
    alert($t('product.downloadTemplateTips1'))
  }
  if (!isLt2M) {
    alert($t('product.downloadTemplateTips2'))
  }
  return extension || (extension2 && isLt2M)
}

const uploadRef = ref(null)
const submitUpload = () => {
  upload = false
  uploadRef.value?.submit()
  if (!upload) {
    ElMessage.error($t('shop.fileNullTip'))
  }
}

const handlePreview = (file) => {
  if (file.response.status) {
    alert($t('product.fileSuccess'))
    emit('refreshDataList')
  } else {
    alert($t('product.fileFail'))
  }
}
// 下载模板
const downloadModel = () => {
  http({
    url: http.adornUrl('/prod/prod/downloadModel'),
    method: 'get',
    responseType: 'blob' // 解决文件下载乱码问题
  }).then(({ data }) => {
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = $t('product.fileName')
    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  })
}

defineExpose({
  init
})

</script>
<style scoped>
.download-btn {
  margin-left: 12px;
}
div :deep(.el-dialog__body) {
  padding-top: 10px;
}
.upload-demo {
  display: inline-block;
}
</style>
